package com.easyfun.healthmagicbox.alarmclock;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import cn.kuaipan.android.openapi.KuaiPanManager;
import cn.kuaipan.android.openapi.tasks.UploadTask;

import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.AlarmClockUploadTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.AlarmClock;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.HealthDateUtil;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.util.PostFile;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.easyfun.healthmagicbox.widget.DialogBuilder;
import com.easyfun.healthmagicbox.widget.CustomDialogUtil;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;

public class AlarmSettingActivity extends BaseActivity implements DatabaseAccess {
	protected static final String TAG = AlarmSettingActivity.class.getSimpleName();


	EditText alarm_time1;
	EditText alarm_cycle1;
	EditText alarm_desc1;
	EditText alarm_time2;
	EditText alarm_cycle2;
	EditText alarm_desc2;
	
	CustomDialogUtil alarmCycle1Diag;
	CustomDialogUtil alarmCycle2Diag;
	CustomDialogUtil selectedDialog;  //this dialog is used for keeping the dialog which is being displayed.

	protected Calendar calendar1 = Calendar.getInstance();
	protected Calendar calendar2 = Calendar.getInstance();
	

	private ArrayList<String> values = new ArrayList<String>();
	ArrayList<String> items = new ArrayList<String>();

	private Button btn_removealarmclock;

	private Button btn_savealarmclock;

	private ImageView volume;

	private ImageView chatting_mode_btn1;
	private RelativeLayout mBottom1;
	private TextView mBtnRcd1;
	private TextView mPlayButton1;
	private boolean btn_vocie1;
	
	private ImageView chatting_mode_btn2;
	private RelativeLayout mBottom2;
	private TextView mBtnRcd2;
	private TextView mPlayButton2;
	private boolean btn_vocie2;
	
	private int flag = 1;
	private LinearLayout del_re;
	private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
	voice_rcd_hint_tooshort;
	private View rcChat_popup;
	private Handler mHandler = new Handler();
	private boolean isShosrt = false;
	private ImageView img1, sc_img1;

	private long startVoiceT, endVoiceT;
	private SoundMeter mSensor;
	private String alarm1soundfilename, alarm2soundfilename;

	
	class MySelectBoxClick implements OnClickListener {
		CustomDialogUtil dialog = null;

		MySelectBoxClick(CustomDialogUtil dialog) {
			this.dialog = dialog;
			
		}

		@Override
		public void onClick(View v) {
			selectedDialog = dialog;
			this.dialog.createDialog(true); //this is single option dialog
		}
	}

	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarmsetting);
		if (!checkPersonId())
			return;
		// addbackButton should after setting content view
		addbackButton(this);
		alarm_time1 = (EditText) findViewById(R.id.alarm_time1);
		alarm_cycle1 = (EditText) findViewById(R.id.alarm_cycle1);
		alarm_desc1 = (EditText) findViewById(R.id.alarm_desc1);

		alarm_time2 = (EditText) findViewById(R.id.alarm_time2);
		alarm_cycle2 = (EditText) findViewById(R.id.alarm_cycle2);
		alarm_desc2 = (EditText) findViewById(R.id.alarm_desc2);

		calendar1.setTimeInMillis(System.currentTimeMillis());
		calendar2.setTimeInMillis(System.currentTimeMillis());
		btn_removealarmclock = (Button) findViewById(R.id.btn_removealarmclock);
		btn_removealarmclock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new DialogBuilder(AlarmSettingActivity.this)
				.setTitle("提示")
				.setMessage("删除所有闹钟?")
				.setButtons("确定","取消", new DialogBuilder.OnDialogButtonClickListener() {
					@Override
					public void onDialogButtonClick(Context context, DialogBuilder builder, Dialog dialog, int dialogId, int which) {
						if (which == BUTTON_LEFT) {
							removeAllAlarm();
						}
					}
					
				}).create().show(); 

			}
		});
		btn_savealarmclock = (Button) findViewById(R.id.btn_savealarmclock);
		btn_savealarmclock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveAlarm();

			}
		});

		alarm_time1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.d(TAG, "click the time button to set time");
				new TimePickerDialog(AlarmSettingActivity.this, timepickListener1,
						calendar1.get(Calendar.HOUR_OF_DAY), calendar1
								.get(Calendar.MINUTE), true).show();
			}
		});

		alarm_time2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.d(TAG, "click the time button to set time 2");
				new TimePickerDialog(AlarmSettingActivity.this, timepickListener2,
						calendar2.get(Calendar.HOUR_OF_DAY), calendar2
								.get(Calendar.MINUTE), true).show();
			}
		});
		items.add("今天");
		values.add("-1");

		items.add("明天");
		values.add("0");
		for (int i = 1; i < 8; i++) {
			items.add("每星期" + i);
			values.add(String.valueOf(i));
		}
		alarmCycle1Diag = new CustomDialogUtil(AlarmSettingActivity.this,
				items, values, alarm_cycle1);
		alarm_cycle1.setOnClickListener(new MySelectBoxClick(alarmCycle1Diag));

		alarmCycle2Diag = new CustomDialogUtil(AlarmSettingActivity.this,
				items, values, alarm_cycle2);
		alarm_cycle2.setOnClickListener(new MySelectBoxClick(alarmCycle2Diag));

		
		chatting_mode_btn1 = (ImageView) this.findViewById(R.id.ivPopUp1);
		mBottom1 = (RelativeLayout) findViewById(R.id.btn_bottom1);
		mBtnRcd1 = (TextView) findViewById(R.id.btn_rcd1);
		mPlayButton1 = (TextView) findViewById(R.id.btn_play1);
		
		chatting_mode_btn2 = (ImageView) this.findViewById(R.id.ivPopUp2);
		mBottom2 = (RelativeLayout) findViewById(R.id.btn_bottom2);
		mBtnRcd2 = (TextView) findViewById(R.id.btn_rcd2);
		mPlayButton2 = (TextView) findViewById(R.id.btn_play2);
		
		rcChat_popup = this.findViewById(R.id.rcChat_popup);

		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);

		volume = (ImageView) this.findViewById(R.id.volume);
		mSensor = new SoundMeter();
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		
		
		//语音文字切换按钮
		chatting_mode_btn1.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				changeVoiceButton(1);				
			}
		});
		chatting_mode_btn2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				changeVoiceButton(2);				
			}
		});
		
		mBtnRcd1.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				//按下语音录制按钮时返回false执行父类OnTouch
				return false;
			}
		});

		mPlayButton1.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String filename = URIConverter.getFilePathFromAppSDCard(AlarmSettingActivity.this, alarm1soundfilename);
				File file = new File(filename);
				if (file.exists()) {
					mSensor.playMusic(filename);
				}else
				{
					Toast.makeText(AlarmSettingActivity.this, "还没有录音！", Toast.LENGTH_SHORT);
					Log.d(TAG, "还没有录音！");
				}
			}
		});

		mPlayButton2.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String filename = URIConverter.getFilePathFromAppSDCard(AlarmSettingActivity.this, alarm2soundfilename);
				File file = new File(filename);
				if (file.exists()) {
					mSensor.playMusic(filename);
				}else
				{
					Toast.makeText(AlarmSettingActivity.this, "还没有录音！", Toast.LENGTH_SHORT);
				}
			}
		});

		loadAlarm();
		changeVoiceButton(1);
		changeVoiceButton(2);
	}
	
	private void changeVoiceButton(int clocknum)
	{
		
		if (clocknum == 1)
		{
			if (btn_vocie1) {
				mBottom1.setVisibility(View.GONE);
				alarm_desc1.setVisibility(View.VISIBLE);
				chatting_mode_btn1
						.setImageResource(R.drawable.chatting_setmode_msg_btn);
				btn_vocie1 = false;

			} else {
				mBottom1.setVisibility(View.VISIBLE);
				alarm_desc1.setVisibility(View.GONE);
				chatting_mode_btn1
						.setImageResource(R.drawable.chatting_setmode_voice_btn);
				btn_vocie1 = true;
			}
		}else
		{
			if (btn_vocie2) {
				mBottom2.setVisibility(View.GONE);
				alarm_desc2.setVisibility(View.VISIBLE);
				chatting_mode_btn2
						.setImageResource(R.drawable.chatting_setmode_msg_btn);
				btn_vocie2 = false;
			} else {
				mBottom2.setVisibility(View.VISIBLE);
				alarm_desc2.setVisibility(View.GONE);
				chatting_mode_btn2
						.setImageResource(R.drawable.chatting_setmode_voice_btn);
				btn_vocie2 = true;
			}
		}
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch(requestCode) {
			case ConstantData.CUSTOM_DIALOG_REQUST_ID:
				selectedDialog.onActivityResult(requestCode, resultCode, data);
				break;
			}
		}
	}

	private TimePickerDialog.OnTimeSetListener timepickListener1 = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker arg0, int h, int m) {
			// 更新按钮上的时间
			alarm_time1.setText(formatTime(h, m));
			// 设置日历的时间，主要是让日历的年月日和当前同步
			calendar1.setTimeInMillis(System.currentTimeMillis());
			// 设置日历的小时和分钟
			calendar1.set(Calendar.HOUR_OF_DAY, h);
			calendar1.set(Calendar.MINUTE, m);
			// 将秒和毫秒设置为0
			calendar1.set(Calendar.SECOND, 0);
			calendar1.set(Calendar.MILLISECOND, 0);
			// 建立Intent和PendingIntent来调用闹钟管理器

		}

	};

	private TimePickerDialog.OnTimeSetListener timepickListener2 = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker arg0, int h, int m) {
			// 更新按钮上的时间
			alarm_time2.setText(formatTime(h, m));
			// 设置日历的时间，主要是让日历的年月日和当前同步
			calendar2.setTimeInMillis(System.currentTimeMillis());
			// 设置日历的小时和分钟
			calendar2.set(Calendar.HOUR_OF_DAY, h);
			calendar2.set(Calendar.MINUTE, m);
			// 将秒和毫秒设置为0
			calendar2.set(Calendar.SECOND, 0);
			calendar2.set(Calendar.MILLISECOND, 0);
			// 建立Intent和PendingIntent来调用闹钟管理器

		}

	};

	private void loadAlarm() {
		Dao<AlarmClock, Integer> alarmDao;
		List<AlarmClock> alarmlist = null;
		try {
			alarmDao = getHelper(this).getAlarmClockDao();
			alarmlist = alarmDao.queryForEq("personID", m_personid);
			DeleteBuilder<AlarmClock, Integer> db = alarmDao.deleteBuilder();
			
			for (AlarmClock alarm : alarmlist) {
				Long starttimeInMill = 0l;
				try
				{
					starttimeInMill = Long.valueOf(alarm
							.getStartTimeInMills());
				}catch(Exception e)
				{
					e.printStackTrace();
					starttimeInMill = 0l;
				}
				Date startTime = new Date(starttimeInMill);
				String startTimeHHmm = HealthDateUtil
						.getAlarmTimeStr(startTime);
				if (alarm.getClockid().equals("1")) {
					alarm_time1.setText(startTimeHHmm);
					calendar1.setTimeInMillis(starttimeInMill);
					alarmCycle1Diag.setValuesInStr(alarm.getCycle());
					alarm_cycle1.setText(alarmCycle1Diag.getItemsInStr());
					if (isVoiceFile(alarm.getDescription()))
					{
						alarm1soundfilename = removeVoiceHeader(alarm.getDescription());
						alarm_desc1.setText("");
					}else
					{	
						alarm1soundfilename = null;
						alarm_desc1.setText(alarm.getDescription());
					}
					
				} else if (alarm.getClockid().equals("2")) {
					alarm_time2.setText(startTimeHHmm);
					calendar2.setTimeInMillis(starttimeInMill);
					alarmCycle2Diag.setValuesInStr(alarm.getCycle());
					alarm_cycle2.setText(alarmCycle2Diag.getItemsInStr());
					if (isVoiceFile(alarm.getDescription()))
					{
						alarm2soundfilename = removeVoiceHeader(alarm.getDescription());
						alarm_desc2.setText("");
					}else
					{	
						alarm2soundfilename = null;
						alarm_desc2.setText(alarm.getDescription());
					}
					
				} else {
					db.where().idEq(alarm.getId());
					db.delete();
				}

			}

			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	private static String VOICEHEADER = "_VoiceFile:";
	private boolean isVoiceFile(String desc)
	{
		return desc.startsWith(VOICEHEADER);
	}

	private String addVoiceHeader(String filename)
	{
		return VOICEHEADER+filename;
	}

	private String removeVoiceHeader(String filename)
	{
		if (isVoiceFile(filename))
		{
			return filename.substring(VOICEHEADER.length());
		}else
		{
			return filename;
		}
	}	
	
	private void uploadSoundFile(String personID,String soundfilename)
	{
		final Map<String, String> params=new HashMap<String, String>();
		final Map<String, File> files = new HashMap<String, File>();
		params.put("data[username]", personID+"_"+soundfilename);
		String filename = URIConverter.getFilePathFromAppSDCard(AlarmSettingActivity.this, soundfilename);
		File file = new File(filename);
		files.put("data[doctorcertification]", file);
		new Thread()
		{
			public void run()
			{
				try {
					String response = PostFile.post("http://www.kangbox.cn/cakephp/doctorPortal/testuploadbond", params, files);
					Log.d(TAG,response);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}
		
	private void saveAlarm() {

		Dao<AlarmClock, Integer> alarmDao = null;
		try {
			alarmDao = getHelper(this).getAlarmClockDao();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		}
		DeleteBuilder<AlarmClock, Integer> db = alarmDao.deleteBuilder();
		
		AlarmClock ac1 = null;
		//if is blank(null), the alarm will be removed.
		if ((alarm_time1.getText() != null)
				&& (alarm_time1.getText().length() > 0)
				&& (alarmCycle1Diag.getValuesInStr() != null)
				&& (alarmCycle1Diag.getValuesInStr().length() > 0)) {
			ac1 = new AlarmClock();
			ac1.setPersonID(m_personid);
			ac1.setClockid("1");
			if (btn_vocie1)
			{
				if (alarm1soundfilename!=null)
					ac1.setDescription(addVoiceHeader(alarm1soundfilename));
				else
					ac1.setDescription("");
			}else
			{
				ac1.setDescription(alarm_desc1.getText().toString());
			}
			//Because the desk clock hardware must have
			//, easy to get clock.
			String hackstr = "";
			if (alarmCycle1Diag.getValuesInStr().charAt(0)!=',')
			{
				hackstr = ","+alarmCycle1Diag.getValuesInStr();
			}else
			{
				hackstr = alarmCycle1Diag.getValuesInStr();
			}
			ac1.setCycle(hackstr);
			ac1.setStartTimeInMills(String.valueOf(calendar1.getTimeInMillis()));
		}else
		{			
			try {
				ac1 = new AlarmClock();
				ac1.setPersonID(m_personid);
				ac1.setClockid("1");
				ac1.setCycle("");
				AlarmClockUploadTask deltask1 = new AlarmClockUploadTask(this, new BasicCommCallback(),
						ac1.getPersonID(),ac1);
				HealthThreadPool.getInstance().execute(deltask1);
				db.where().eq("clockid", "1");
				db.delete();
				ac1 = null;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		AlarmClock ac2 = null;
		if ((alarm_time2.getText() != null)
				&& (alarm_time2.getText().length() > 0)
				&& (alarmCycle2Diag.getValuesInStr() != null)
				&& (alarmCycle2Diag.getValuesInStr().length() > 0)) {
			ac2 = new AlarmClock();
			ac2.setPersonID(m_personid);
			ac2.setClockid("2");
			if (btn_vocie2)
			{
				if (alarm2soundfilename!=null)
					ac2.setDescription(addVoiceHeader(alarm2soundfilename));
				else
					ac2.setDescription("");
			}else
			{
				ac2.setDescription(alarm_desc2.getText().toString());
			}
			String hackstr = "";
			if (alarmCycle2Diag.getValuesInStr().charAt(0)!=',')
			{
				hackstr = ","+alarmCycle2Diag.getValuesInStr();
			}else
			{
				hackstr = alarmCycle2Diag.getValuesInStr();
			}
			ac2.setCycle(hackstr);
			ac2.setStartTimeInMills(String.valueOf(calendar2.getTimeInMillis()));
		}else
		{
			try {
				db.where().eq("clockid", "2");
				db.delete();
				ac2 = new AlarmClock();
				ac2.setPersonID(m_personid);
				ac2.setClockid("2");
				ac2.setCycle("");
				AlarmClockUploadTask deltask2 = new AlarmClockUploadTask(this, new BasicCommCallback(),
						ac2.getPersonID(),ac2);
				HealthThreadPool.getInstance().execute(deltask2);
				ac2 = null;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		try {
			
			if (ac1 != null)
			{
				db.where().eq("clockid", ac1.getClockid());
				db.delete();
				alarmDao.create(ac1);
				AlarmClockUploadTask uptask = new AlarmClockUploadTask(this, new BasicCommCallback(),
								ac1.getPersonID(),ac1);
				HealthThreadPool.getInstance().execute(uptask);
				if (alarm1soundfilename!=null)
				{
					uploadSoundFile(m_personid,alarm1soundfilename);
					/*KuaiPanManager.getInstance(AlarmSettingActivity.this)
						.uploadFile(m_personid,
									URIConverter.getFilePathFromAppSDCard(AlarmSettingActivity.this, 
												alarm1soundfilename),
									alarm1soundfilename);
					*/
				}
				
			}
			
			if (ac2 != null)
			{
				db.where().eq("clockid", ac2.getClockid());
				db.delete();
				alarmDao.create(ac2);
				AlarmClockUploadTask uptask2 = new AlarmClockUploadTask(this, new BasicCommCallback(),
						ac2.getPersonID(),ac2);
				HealthThreadPool.getInstance().execute(uptask2);
				if (alarm2soundfilename!=null)
				{
					uploadSoundFile(m_personid,alarm2soundfilename);
					/*
					KuaiPanManager.getInstance(AlarmSettingActivity.this)
						.uploadFile(m_personid,
									URIConverter.getFilePathFromAppSDCard(AlarmSettingActivity.this, 
												alarm2soundfilename),
									alarm2soundfilename);
					*/
				}
			}

			if (PersonProfileCache.getInstance(AlarmSettingActivity.this).getPersonID(AlarmSettingActivity.this)
					.equals(m_personid)) {

				if (ac1 != null)
					setAlarm(ac1);

				if (ac2 != null)
					setAlarm(ac2);
			}else
			{
				if ((ac1 != null)||(ac2 != null))
					Toast.makeText(AlarmSettingActivity.this, "闹钟成功保存！",Toast.LENGTH_SHORT).show();
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	private void removeAllAlarm() {
		Dao<AlarmClock, Integer> alarmDao;
		alarm_time1.setText("");
		alarm_desc1.setText("");
		alarm_cycle1.setText("");
		alarm_time2.setText("");
		alarm_desc2.setText("");
		alarm_cycle2.setText("");
		try {
			alarmDao = getHelper(this).getAlarmClockDao();
			DeleteBuilder<AlarmClock, Integer> delBuilder = alarmDao
					.deleteBuilder();
			delBuilder.where().eq("personID", m_personid);
			delBuilder.delete();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		AlarmClock ac2 = new AlarmClock();
		ac2.setPersonID(m_personid);
		ac2.setClockid("1");
		ac2.setCycle("");
		AlarmClockUploadTask deltask1 = new AlarmClockUploadTask(this, new BasicCommCallback(),
				ac2.getPersonID(),ac2);
		HealthThreadPool.getInstance().execute(deltask1);
		
		//---------------------------------------------------
		ac2.setClockid("2");
		AlarmClockUploadTask deltask2 = new AlarmClockUploadTask(this, new BasicCommCallback(),
				ac2.getPersonID(),ac2);
		HealthThreadPool.getInstance().execute(deltask2);
		
		if (PersonProfileCache.getInstance(AlarmSettingActivity.this).getPersonID(AlarmSettingActivity.this).equals(m_personid)) {
			cancelAlarm(1);
			cancelAlarm(2);
		}
		Toast.makeText(AlarmSettingActivity.this, "闹钟已经取消！", Toast.LENGTH_SHORT).show();
	}

	private CharSequence formatTime(int h, int m) {
		String hours = String.valueOf(h);
		String minutes = String.valueOf(m);
		if (hours.length() == 1) {
			hours = "0" + hours;
		}
		if (minutes.length() == 1) {
			minutes = "0" + minutes;
		}
		return hours + ":" + minutes;
	}

	private void setAlarm(AlarmClock ac) {

		Intent intent = new Intent(AlarmSettingActivity.this, AlarmReceiver.class);		

		intent.putExtra(ConstantData.HMBPERSONID, m_personid);
		intent.putExtra("cycle", ac.getCycle());
		intent.putExtra("startTime", ac.getStartTimeInMills());
		intent.putExtra("alarmNum", ac.getClockid());
		intent.putExtra("alarmDesc", ac.getDescription());		

		PendingIntent pendingIntent = PendingIntent.getBroadcast(
				AlarmSettingActivity.this, Integer.valueOf(ac.getClockid()), intent, 
				PendingIntent.FLAG_CANCEL_CURRENT
				);

		// 获取闹钟管理器
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		// 设置闹钟
		// setting time is in pass, so have to figure out new timer
		long repeat2 = AlarmRepeatCalculater.getNextAlarmTime(ac);

		if (repeat2 == 0)
			return;
		alarmManager.set(AlarmManager.RTC_WAKEUP, repeat2, pendingIntent);

		String timeStr = HealthDateUtil.formatDate(new Date(repeat2),
				"yyyy-MM-dd HH:mm:ss");
		Toast.makeText(AlarmSettingActivity.this, "设置闹钟的时间为：" + timeStr,
				Toast.LENGTH_SHORT).show();
		Log.d(TAG, "set the time to " + timeStr);
	}

	public void cancelAlarm(int alarmNum) {
		Intent intent = new Intent(AlarmSettingActivity.this, AlarmReceiver.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(
				AlarmSettingActivity.this, alarmNum, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
		
	}
	
	//按下语音录制按钮时
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		//if (!Environment.getExternalStorageDirectory().exists()) {
		//	Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
		//	return false;
		//}
		if (touchEventAlarm(event,(short)1))
			touchEventAlarm(event,(short)2);
		
		return super.onTouchEvent(event);
	}

	private boolean touchEventAlarm(MotionEvent event, short clockid)
	{
		TextView mBtnRcd;
		boolean btn_vocie = false;
		String alarmsoundfilename = null;
		if (clockid == 1)
		{
			btn_vocie = btn_vocie1;
			mBtnRcd = mBtnRcd1;
			alarmsoundfilename = alarm1soundfilename;
		}
		else
		{
			btn_vocie = btn_vocie2;
			mBtnRcd = mBtnRcd2;
			alarmsoundfilename = alarm2soundfilename;
		}
		if (btn_vocie) {
			System.out.println("1");
			int[] location = new int[2];
			mBtnRcd.getLocationInWindow(location); // 
			int btn_rc_Y = location[1];
			int btn_rc_X = location[0];
			int[] del_location = new int[2];
			del_re.getLocationInWindow(del_location);
			int del_Y = del_location[1];
			int del_x = del_location[0];
			if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
				
				if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内
					System.out.println("start to record");
					mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_pressed);
					rcChat_popup.setVisibility(View.VISIBLE);
					voice_rcd_hint_loading.setVisibility(View.VISIBLE);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					voice_rcd_hint_tooshort.setVisibility(View.GONE);
					mHandler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								voice_rcd_hint_loading.setVisibility(View.GONE);
								voice_rcd_hint_rcding
										.setVisibility(View.VISIBLE);
							}
						}
					}, 300);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
				    startVoiceT = SystemClock.currentThreadTimeMillis(); 
					Date date=new Date();  
				    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");  

					alarmsoundfilename = formatter.format(date) + ".amr";
					
					startRecord(URIConverter
							.getFilePathFromAppSDCard(
									AlarmSettingActivity.this,alarmsoundfilename));
					if (clockid == 1)
					{
						alarm1soundfilename=alarmsoundfilename;
					}
					else
					{
						alarm2soundfilename=alarmsoundfilename;
					}
					flag = 2;
				}
				return false;
			} else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成
				System.out.println("4 stop recording!");
				mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_nor);
				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					//delete
					rcChat_popup.setVisibility(View.GONE);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					stopRecord();
					flag = 1;
					File file = new File(URIConverter
							.getFilePathFromAppSDCard(
									AlarmSettingActivity.this,alarmsoundfilename));
					if (file.exists()) {
						file.delete();
					}
					alarmsoundfilename = null;
				} else {
					//stop record
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stopRecord();
					endVoiceT = SystemClock.currentThreadTimeMillis();
					flag = 1;
					int time = (int) ((endVoiceT - startVoiceT) / 100);
					if (time < 1) {
						//too short
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						mHandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);

						alarmsoundfilename = null;
					}
					
					rcChat_popup.setVisibility(View.GONE);

				}
				return false;
			}
			if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
				System.out.println("5 out of range");
				Animation mLitteAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc);
				Animation mBigAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc2);
				img1.setVisibility(View.GONE);
				del_re.setVisibility(View.VISIBLE);
				del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
					sc_img1.startAnimation(mLitteAnimation);
					sc_img1.startAnimation(mBigAnimation);
				}
			} else {

				img1.setVisibility(View.VISIBLE);
				del_re.setVisibility(View.GONE);
				del_re.setBackgroundResource(0);
			}
		}
		return true;
	}
	private static final int POLL_INTERVAL = 300;

	private Runnable mPollTask = new Runnable() {
		public void run() {
			//double amp = mSensor.getAmplitude();
			//updateDisplay(amp);
			mHandler.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

/*
	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};
*/
	
	private void startRecord(String name) {
		mSensor.startRecord(name);
		mHandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stopRecord() {
		//mHandler.removeCallbacks(mSleepTask);
		mHandler.removeCallbacks(mPollTask);
		mSensor.stop();
		volume.setImageResource(R.drawable.amp1);
	}

	private void updateDisplay(double signalEMA) {
		
		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);
			
			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}
}
